<template>
  <CrudTable
    :buttons="[]"
    row-selection-type="multiple"
    :columns="tableColumns"
    @currentChange="handleSelectChange"
    :tableData="pageData.tableData.records"
    :loading="pageData.loading"
    :pagination="pageData.pagination"
    @pageChange="handlePageChange"
    :showRefresh="true"
    :showExport="false"
    @refreshData="handleTableRefresh"
  >
    <template #operations>
      <InputSelect
        :value="pageData.filterValue.orderName"
        @onClick="handleOrderShow"
        placeholder="点击右侧按钮选择订单..."
      />
      <t-space size="small">
        <t-button theme="primary" @click="filterChange">查询</t-button>
        <t-button theme="warning" @click="handleFilterReset">重置</t-button>
      </t-space>
    </template>
    <template #rowOperations="{ row }">
      <div class="crud-table__row_operations">
        <t-link theme="warning" variant="text" @click="handleOperateApplyPay(row)">申请还款</t-link>
      </div>
    </template>
  </CrudTable>

  <SelectTable
    v-if="pageData.order.show"
    :loading="pageData.order.loading"
    :showDialog="pageData.order.show"
    title="选择订单"
    width="65vw"
    rowSelectionType="single"
    :tableData="pageData.order.data.records"
    :columns="orderColumns"
    @onConfirm="handleOrderConfirm"
    @onCancel="handleOrderClose"
    :pagination="pageData.order.pagination"
    @page-change="handleOrderPageChange"
  >
    <template #toolkit>
      <t-form class="crud-form" :data="pageData.order.filterValue">
        <t-space direction="vertical" style="width: 100%" size="small">
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="客户" name="customerMainName">
                <InputSelect :value="pageData.order.filterValue.customerMainName" @onClick="handleCustomerShow" />
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="订单号" name="orderName">
                <t-input v-model="pageData.order.filterValue.orderName" placeholder="输入订单号搜索..." />
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="订单名称" name="orderName">
                <t-input v-model="pageData.order.filterValue.orderName" placeholder="输入订单名称搜索..." />
              </t-form-item>
            </t-col>
          </t-row>
          <div class="crud-form__operations">
            <t-button theme="primary" @click="handleOrderFilterChange">查询</t-button>
            <t-button theme="warning" @click="handleOrderFilterReset">重置</t-button>
          </div>
        </t-space>
      </t-form>
    </template>
  </SelectTable>

  <SelectTable
    v-if="pageData.customer.show"
    :loading="pageData.customer.loading"
    :showDialog="pageData.customer.show"
    title="选择客户"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.customer.data.records"
    :columns="customerColumns"
    @onConfirm="handleCustomerConfirm"
    @onCancel="handleCustomerClose"
    :pagination="pageData.customer.pagination"
    :filter-value="pageData.customer.filterValue"
    @filter-change="handleCustomerFilterChange"
    @page-change="handleCustomerPageChange"
    :zIndex="2600"
  />

  <ApplyRePay
    v-if="pageData.showApplyRePay"
    :showDialog="pageData.showApplyRePay"
    :id="pageData.selectedRowId"
    :row="pageData.selectedRow"
    @onClose="handleApplyRePayClose"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, defineAsyncComponent } from "vue";
import { MessagePlugin } from "tdesign-vue-next";

// TS 类型文件
import type { ICrudTableDataPage, ISelectTableGroups } from "@/types";

// 工具函数
import { http } from "@/utils/fetch";

// 常量
import { PAGINATION_VALUE } from "@/common/constants";

// API
import { getOrderList } from "@/api/order";
import { getCustomerList } from "@/api/cas";

// 业务数据
import { tableColumns } from "./components/columns";
import { tableColumns as orderColumns } from "../Order/components/columns";
import { tableColumns as customerColumns } from "@/pages/Dashboard/CAS/Customer/components/columns";

// 动态组件
// const EditForm = defineAsyncComponent(() => import("./components/EditForm.vue"));
const ApplyRePay = defineAsyncComponent(() => import("./components/ApplyRePay.vue"));

const GET_LIST_PATH = "/billing/findAll"; // 查询信息接口
// const DELETE_ITEM_PATH = "/order/delete"; // 删除接口

const pageData = reactive({
  loading: false,
  tableData: {} as ICrudTableDataPage,
  selectedRow: {} as Record<string, any>,
  selectedRowsEvent: {} as Record<string, any>,
  selectedRowId: "",
  showEditForm: false,
  editFormMode: "",
  showApplyRePay: false,
  filterValue: {
    orderName: "",
    orderId: ""
  } as Record<string, any>,
  pagination: {
    pageSize: 20,
    total: 0,
    current: 1
  },
  customer: {
    show: false,
    loading: false,
    data: {} as ICrudTableDataPage,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    },
    filterValue: {}
  } as ISelectTableGroups,
  order: {
    show: false,
    loading: false,
    data: {} as ICrudTableDataPage,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    },
    filterValue: { customerMainName: "", customerId: "", status: [], orderNo: "", orderName: "" }
  } as ISelectTableGroups
});

// 表格操作按钮配置
// const tableButtons = computed(() => [
//   {
//     name: "新增",
//     click: () => {
//       handleOperateRow("new");
//     }
//   }
// ]);

// 表格列配置

// 获取列表数据
const findAllList = async () => {
  pageData.loading = true;
  const resultData = await http(
    "POST",
    `${GET_LIST_PATH}?page=${pageData.pagination.current}&pageSize=${pageData.pagination.pageSize}`,
    pageData.filterValue
  );
  if (resultData.code === 200) {
    pageData.tableData = resultData.data;
    pageData.pagination.total = resultData.data.total;
    pageData.pagination.current = resultData.data.current;
    pageData.pagination.pageSize = resultData.data.size;
    pageData.loading = false;
  }
};

const handlePageChange = (pageInfo: Record<string, any>) => {
  pageData.pagination.pageSize = pageInfo.pageSize;
  pageData.pagination.current = pageInfo.current;
  findAllList();
};

// 获取订单选择列表的方法
const handleOrderShow = () => {
  pageData.order.show = true;
  getOrderData();
};

const getOrderData = async () => {
  pageData.order.loading = true;
  const resultData = await getOrderList(
    pageData.order.pagination.current,
    pageData.order.pagination.pageSize,
    pageData.order.filterValue
  );

  if (resultData.code === 200) {
    pageData.order.data = resultData.data;
    pageData.order.pagination.total = resultData.data.total;
    pageData.order.pagination.current = resultData.data.current;
    pageData.order.pagination.pageSize = resultData.data.size;
    pageData.order.loading = false;
  }
};

const handleOrderPageChange = (pageInfo: Record<string, any>) => {
  pageData.order.pagination.pageSize = pageInfo.pageSize;
  pageData.order.pagination.current = pageInfo.current;
  getOrderData();
};

const handleOrderFilterChange = () => {
  pageData.order.pagination = structuredClone(PAGINATION_VALUE);
  getOrderData();
};

const handleOrderFilterReset = () => {
  pageData.order.filterValue = { customerMainName: "", customerId: "", status: [], orderNo: "", orderName: "" };
  pageData.order.pagination = structuredClone(PAGINATION_VALUE);
  getOrderData();
};

const handleOrderConfirm = (e: Record<string, any>) => {
  // console.log(e);
  pageData.filterValue.orderId = e.options.currentRowData.id;
  pageData.filterValue.orderName = e.options.currentRowData.orderName;
  pageData.order.show = false;
};

const handleOrderClose = () => {
  pageData.order.show = false;
};

// 获取客户选择列表的方法
const handleCustomerShow = () => {
  pageData.customer.show = true;
  getCustomerData();
};

const getCustomerData = async () => {
  pageData.customer.loading = true;
  const resultData = await getCustomerList(
    pageData.customer.pagination.current,
    pageData.customer.pagination.pageSize,
    pageData.customer.filterValue
  );

  if (resultData.code === 200) {
    pageData.customer.data = resultData.data;
    pageData.customer.pagination.total = resultData.data.total;
    pageData.customer.pagination.current = resultData.data.current;
    pageData.customer.pagination.pageSize = resultData.data.size;
    pageData.customer.loading = false;
  }
};

const handleCustomerPageChange = (pageInfo: Record<string, any>) => {
  pageData.customer.pagination.pageSize = pageInfo.pageSize;
  pageData.customer.pagination.current = pageInfo.current;
  getCustomerData();
};

const handleCustomerFilterChange = (filters: Record<string, any>) => {
  pageData.filterValue = filters;
  pageData.customer.pagination = structuredClone(PAGINATION_VALUE);
  getCustomerData();
};

const handleCustomerConfirm = (e: Record<string, any>) => {
  pageData.order.filterValue.customerId = e.options.currentRowData.id;
  pageData.order.filterValue.customerMainName = e.options.currentRowData.name;
  pageData.customer.show = false;
};

const handleCustomerClose = () => {
  pageData.customer.show = false;
};

// 过滤事件触发函数
const filterChange = () => {
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  findAllList();
};

const handleFilterReset = () => {
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  pageData.filterValue = { customerMainName: "", customerId: "", status: [], orderNo: "", orderName: "" };
  findAllList();
};

const handleTableRefresh = () => {
  pageData.selectedRow = {};
  pageData.selectedRowId = "";
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  pageData.filterValue = { orderId: "", orderNo: "" };
  findAllList();
};

// const handleRowDbClick = (context: Record<string, any>) => {
//   handleOperateRow("view", context.row);
// };

// const handleOperateRow = (mode: string, row?: Record<string, any>) => {
//   if (mode !== "delete") {
//     if (mode === "new") {
//       pageData.selectedRow = {};
//       pageData.selectedRowId = "";
//     } else {
//       pageData.selectedRow = row!;
//       pageData.selectedRowId = row!.id;
//     }
//     pageData.editFormMode = mode;
//     pageData.showEditForm = true;
//   } else if (mode === "delete") {
//     const confirmDialog = DialogPlugin({
//       header: "警告",
//       body: "确定要删除这一条数据吗？",
//       confirmBtn: "确定",
//       cancelBtn: "取消",
//       onConfirm: async () => {
//         const deleteData = await http("DELETE", `${DELETE_ITEM_PATH}?id=${row!.id}`);
//         if (deleteData.code === 200) {
//           MessagePlugin.success("删除成功！");
//           findAllList();
//           confirmDialog.hide();
//         }
//       },
//       onClose: () => {
//         confirmDialog.hide();
//       }
//     });
//   } else {
//     MessagePlugin.error("错误：未知的表格操作模式。");
//   }
// };

const handleOperateApplyPay = (row: Record<string, any>) => {
  pageData.selectedRow = row;
  pageData.selectedRowId = row.id;
  pageData.showApplyRePay = true;
};

const handleApplyRePayClose = (e: string) => {
  if (e === "success") {
    MessagePlugin.success("申请付款成功！");
    findAllList();
  }
  pageData.showApplyRePay = false;
};

const handleSelectChange = (e: Record<string, any>) => {
  pageData.selectedRowsEvent = e;
};

findAllList();
</script>
